package com.iflytek.jcy.supervise.job.component.web;

import java.lang.reflect.Method;

import com.iflytek.jcy.supervise.job.common.pojo.CommonResponse;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 对含有{@link CommonResp} 且 返回类型不是{@link CommonResponse}的方法,
 * 将其返回值使用{@link CommonResponse}包装为成功响应
 * @author <a href=mailto:ktyi@iflytek.com>伊开堂</a>
 * @date 2020/3/3 15:43
 */
@ControllerAdvice
public class JsonResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        // 有@CommonResp注解 且 返回值不是Result
        Method method = methodParameter.getMethod();
        CommonResp annotation = method.getAnnotation(CommonResp.class);
        Class<?> returnType = methodParameter.getMethod().getReturnType();
        return annotation != null && !CommonResponse.class.isAssignableFrom(returnType);
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass,
            ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        return o instanceof CommonResponse ? o : CommonResponse.success(o);
    }

}
